package com.example.livedatautilsdemo.helper;

import android.os.CountDownTimer;

import androidx.lifecycle.MutableLiveData;

/**
 * @author: njb
 * @date: 2023/8/6 23:37
 * @desc:
 */
public class LiveDataTimeHelper extends MutableLiveData<Long> {
    private CountDownTimer countDownTimer;

    public void startCountDown(long millisInFuture, long countDownInterval) {
        countDownTimer = new CountDownTimer(millisInFuture, countDownInterval) {
            @Override
            public void onTick(long millisUntilFinished) {
                setValue(millisUntilFinished / 1000);
            }

            @Override
            public void onFinish() {
                setValue(0L);
            }
        };
        countDownTimer.start();
    }

    public void stopCountDown() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        stopCountDown();
    }
}
